#!/bin/bash -e
#
# Universal mirroring repository tool.
#
# @package    Bash
# @author     Kai Kimera <mail@kai.kim>
# @copyright  2023 Kai Kimera
# @license    MIT
# @version    0.0.1
# @link       https://github.com/ghastore
# -------------------------------------------------------------------------------------------------------------------- #

# -------------------------------------------------------------------------------------------------------------------- #
# CONFIGURATION.
# -------------------------------------------------------------------------------------------------------------------- #

# Vars.
SRC_REPO="${1}"
SRC_USER="${2}"
SRC_TOKEN="${3}"
DST_REPO="${4}"
DST_USER="${5}"
DST_TOKEN="${6}"

# Apps.
git="$( command -v git )"

# Dirs.
d_src="/root/git/src"

# -------------------------------------------------------------------------------------------------------------------- #
# INITIALIZATION.
# -------------------------------------------------------------------------------------------------------------------- #

init() {
  mirror
}

# -------------------------------------------------------------------------------------------------------------------- #
# GIT: MIRROR.
# -------------------------------------------------------------------------------------------------------------------- #

mirror() {
  echo "--- [GIT] CLONE: ${SRC_REPO#https://}"

  local src="https://${SRC_USER}:${SRC_TOKEN}@${SRC_REPO#https://}"
  local dst="https://${DST_USER}:${DST_TOKEN}@${DST_REPO#https://}"

  ${git} clone --mirror "${src}" "${d_src}" \
    && _pushd "${d_src}" || exit 1
  ${git} remote add 'dst' "${dst}"
  ${git} push -f --mirror 'dst'

  _popd || exit 1
}

# -------------------------------------------------------------------------------------------------------------------- #
# ------------------------------------------------< COMMON FUNCTIONS >------------------------------------------------ #
# -------------------------------------------------------------------------------------------------------------------- #

# Pushd.
_pushd() {
  command pushd "$@" > /dev/null || exit 1
}

# Popd.
_popd() {
  command popd > /dev/null || exit 1
}

# -------------------------------------------------------------------------------------------------------------------- #
# -------------------------------------------------< RUNNING SCRIPT >------------------------------------------------- #
# -------------------------------------------------------------------------------------------------------------------- #

init "$@"; exit 0
